package com.csd.controller;

import com.csd.common.JsonBean;
import com.csd.dto.ActionResult;
import com.csd.dto.UserResult;
import com.csd.pojo.SysCar;
import com.csd.pojo.SysUser;
import com.csd.service.SysUserService;
import com.csd.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @ Author :lihainan
 * @ ClassNmae :UserController
 * @ Description :TODO
 * @ Date :2020/12/22
 * @ Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 登录校验
     */
    @RequestMapping("/loginUser")
    @ResponseBody
    public JsonBean showLogin(String tel, String password, HttpSession session) {
        JsonBean bean = null;
        try {
            SysUser user = sysUserService.login(tel,password);
            session.setAttribute("user",user);
            bean = JsonUtils.createJsonBean(1, user);
        } catch (Exception e) {
            bean = JsonUtils.createJsonBean(0, e.getMessage());
        }
        return bean;
    }

    @RequestMapping("/register")
    @ResponseBody
    public ActionResult showRegister(SysUser sysUser){
        ActionResult actionResult = null ;
        System.out.println(sysUser);
        try {
            int code = sysUserService.register(sysUser);
            actionResult = JsonUtils.actionResult(200,"登录成功",null,1);
        }catch (Exception e){
            actionResult = JsonUtils.actionResult(200,e.getMessage(),null,0);
        }


        return actionResult;
    }
    @RequestMapping(value = "/getUser",method = RequestMethod.GET)
    @ResponseBody
    public UserResult findUserById(HttpSession session){
        SysUser user = (SysUser) session.getAttribute("user");
        if (user!=null){
            Integer id = user.getId();
            SysUser user1 = sysUserService.findUserById(id);
            return new UserResult(200,"find success",user1,1);
        }else{
            return new UserResult(500,"暂未登录",null,0);
        }

    }
}
